import network
import machine
import ujson
from usocket import socket

# Config
ap_ssid     = 'CSTXESP32S3'
ap_password = '88888888'
# 设置ap的身份验证模式
ap_mode     = 4
ap = network.WLAN(network.AP_IF)
ap.active(True)
ap.config(essid = ap_ssid, password = ap_password, authmode = ap_mode)


# LED配置
led_pin = 2  # 根据实际硬件连接调整
led = machine.Pin(led_pin, machine.Pin.OUT)


# 获取本地IP地址
local_ip = ap.ifconfig()[0]
print('Local IP address:', local_ip)

# 创建简单的Web服务器
def parse_request(request):
    # 解析POST请求，获取LED颜色
    content_length = request.find(b'Content-Length:')
    if content_length != -1:
        end_of_line = request.find(b'\r\n', content_length)
        length = int(request[content_length + 15:end_of_line])
        start_of_data = end_of_line + 4
        data = request[start_of_data:start_of_data + length]
        return ujson.loads(data.decode('utf-8'))
    return None

def handle_request(client_socket):
    # 处理客户端请求
    request = client_socket.recv(1024)
    if request:
        led_color = parse_request(request)
        if led_color:
            # 控制LED颜色
            led.value(led_color)
            response = 'HTTP/1.1 200 OK\r\n\r\nLED color set to {}'.format(led_color)
        else:
            response = 'HTTP/1.1 400 Bad Request\r\n\r\nInvalid request format'
        client_socket.send(response)
    client_socket.close()

def start_web_server():
    # 启动Web服务器
    server_socket = socket()
    server_socket.bind(('0.0.0.0', 80))
    server_socket.listen(5)
    print('Web server is running')

    while True:
        client_socket, addr = server_socket.accept()
        print('Client connected from', addr)
        handle_request(client_socket)

start_web_server()